package com.dtflys.easyel.parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ETokenStream {
    
    private final static int TOKEN_BUFF_SIZE = 128;
    
    private final static int LAST_BUFF_SIZE = 8;
    
    private final ELexer lexer;
    
    private List<EToken> tokenBuff = new ArrayList<>();
    
    private int currentIndex = 0;
    
    public ETokenStream(final ELexer lexer) {
        this.lexer = lexer;
    }
    
    public EToken peek(final int n) {
        final int index = currentIndex + n;
        if (index < 0) {
            return null;
        }
        return tokenBuff.get(currentIndex + n);
    }
    
    public EToken nextToken() throws IOException {
        if (currentIndex < tokenBuff.size()) {
            tokenBuff.remove(0);
            return tokenBuff.get(currentIndex++);
        }
        return lexer.handleEOF();
    }
    
    public void refreshTokenBuff() throws IOException {
        List<EToken> buff = new ArrayList<>();
        final EToken token = lexer.nextToken();
        if (tokenBuff != null && !tokenBuff.isEmpty()) {
            final int lastBuffSize = tokenBuff.size();
            int len = Math.min(lastBuffSize, LAST_BUFF_SIZE);
            for (int i = 0; i < len; i++) {
                buff.add(tokenBuff.get(lastBuffSize - len + i));
            }
        }
    }

    public ELexer getLexer() {
        return lexer;
    }
}
